/**
  扩展一个http模块
**/

layui.define(['laytpl', 'layer','upload', 'table'],function(exports){ //提示：模块也可以依赖其它模块，如：layui.define('layer', callback);
    var  $ = layui.jquery,
    uploadInst = layui.upload,
    table = layui.table,
    obj = {
     ts: new Date().getTime(),
     verifyToken:function(){ //校验登录
     },
     exitToken:function(){ //退出登录

     },
     httpajax:function(url,data,type="GET",callback)
     { //退出登录
        // console.error("authToken----",layui.data(obj.token)['token']);
        console.error("执行请求----",url,data,type);
        $.ajax({
          type:type,
          url:url,
          data:data,
          dataType: 'json',
          // beforeSend: function(request) {
          //     request.setRequestHeader("Authorization", layui.data(obj.token)['token']);
          // },
          success: function(result) {
            console.error("回调种---请求-完成---",result);
            callback(result);
            // return result;
          },
          error: function(e, code){
              console.error("e-成---",e,"ecode---",code);
              var error = JSON.stringify(e.responseJSON.errors);
              layer.alert('请求异常，请重试<br><cite>错误信息：</cite>'+ error);
              return false;
          }
      });
     },
     httpFetch: async function(url,data,csrf,type="GET",callback)
     {
         console.error("执行请求----",url,data,type);
         const response = await fetch(url, {
             method: type, // *GET, POST, PUT, DELETE, etc.
             headers: {
                 "X-CSRF-TOKEN":csrf
             },
             body: JSON.stringify(data) // body data type must match "Content-Type" header
         });
         let josn = await response.json();
         console.error("回调种---请求-完成---josn", josn);
         callback(josn);
     },
     getQueryString:function(name){
        let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        let r = window.location.search.substr(1).match(reg);
        if (r != null) {
            return decodeURIComponent(r[2]);
        };
        return null;
     },
     open:function(title,url){
        var index = layer.open({
            title: title,
            type: 2,
            shade: 0.2,
            maxmin:true,
            shadeClose: true,
            area: ['100%', '100%'],
            content:url,
        });
        $(window).on("resize", function () {
            layer.full(index);
        });
     },
     render:function(url,cols,resulti,limit=15,page=true){
          table.render({
              elem: '#currentTableId',
              url: url,
              toolbar: '#toolbarDemo',
              defaultToolbar: ['filter', 'exports', 'print', {
                  title: '提示',
                  layEvent: 'LAYTABLE_TIPS',
                  icon: 'layui-icon-tips'
              }],
              cols: cols,
              where: resulti,
              // headers: { //通过 request 头传递
              //     Authorization:  layui.data(obj.token)['token'],
              // },
              done: function(res, curr, count){
                //如果是异步请求数据方式，res即为你接口返回的信息。
                //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
                console.log(res);
                //得到当前页码
                console.log(curr);
                //得到数据总量
                console.log(count);
                if(res.code == 403){
                  layer.alert('请求异常，请重试<br><cite>错误信息：</cite>'+ res.msg);
                  window.location.href = obj.loginpage;
                }
              },
              limits: [10, 15, 20, 25, 50, 100,1000],
              limit: limit,
              page: page,
              skin: 'line'
        });
     },
     uplode:function(cateBtn,url,csrf,callback){
        uploadInst.render({
            elem: '#'+cateBtn,
            url:url,
            headers: {
                'X-CSRF-TOKEN': csrf
            },
            accept: 'images',
            field: "file",
            type: 'images',
            exts: 'jpg|png|gif',
            done: function(result){
                callback(result);
                return result;
            },
            error: function(e, code){
                layer.alert('请求异常，请重试<br><cite>错误信息：</cite>'+ code);
                return false;
            }
        });
     }
      //根据自己项目的端口而定
    };

    //输出test接口
    exports('http', obj);
  });
